package cn.com.winning.ecare.utils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;

import cn.com.winning.ecare.activity.GhSeven;
import cn.com.winning.ecare.activity.R;
import cn.com.winning.ecare.alipay.Keys;
import cn.com.winning.ecare.alipay.Result;
import cn.com.winning.ecare.alipay.Rsa;
import cn.com.winning.ecare.common.MyApplication;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UtilPay {
	 
	 public static final String TAG = "alipay-sdk";
	 public Activity mActivity = null;
	 private static final int RQF_PAY = 1;
	 private static final int RQF_LOGIN = 2;
	
	 private String body;
	 private String subject;
	 private String ghdh;
	 private String url;
	 
	public void android_pay (String url,String ghdh,double coin,Activity Activity, String body, String subject){
		mActivity=Activity;
		this.body=body;
		this.subject=subject;
		this.ghdh = ghdh;
		this.url = url;
		if (!is_can_internet (mActivity)){
			    
	         fiapHandler.sendEmptyMessage(1);
	         return;
	     }
	try {
		String info = getNewOrderInfo(coin);
		String sign = Rsa.sign(info, Keys.getPRIVATE());//
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		Log.i("ExternalPartner", "start pay");
		// start the pay.
		Log.i(TAG, "info = " + info);
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(mActivity, mHandler);
				
				//设置为沙箱模式，不设置默认为线上环境
				//alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Log.i(TAG, "result = " + result);
				Message msg = new Message();
				msg.what = RQF_PAY;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		}.start();
	} catch (Exception ex) {
		ex.printStackTrace();
		Toast.makeText(mActivity, R.string.remote_call_failed,
				Toast.LENGTH_SHORT).show();
	}
		
	}
	
	 public boolean is_can_internet (final Context context){//网络判断
	     try{
	         ConnectivityManager manger = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
	         NetworkInfo info = manger.getActiveNetworkInfo ();
	         
	         return (info != null && info.isConnected ());
	     } catch (Exception e){
	    
	         return false;
	     }
	 }
	 
	 private Handler fiapHandler = new Handler(){

		 public void handleMessage(Message msg) {
		 if (msg.what == 1) {
		 new AlertDialog.Builder (mActivity).setTitle ("提示").setMessage ("连接不到网络。").setPositiveButton ("确定", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		//TODO Auto-generated method stub
		Intent intent = new Intent(
		"android.settings.WIFI_SETTINGS");
		mActivity.startActivity(intent);
		}
		}).create ().show ();
		}
		 };
		 };

	 private String getSignType() {
				return "sign_type=\"RSA\"";
			}
	 
	 private String getNewOrderInfo(double position) {
			StringBuilder sb = new StringBuilder();
			sb.append("partner=\"");
			sb.append(Keys.getDEFAULT_PARTNER());
			sb.append("\"&out_trade_no=\"");
		//	sb.append(getOutTradeNo());
			sb.append(ghdh);
			sb.append("\"&subject=\"");
			sb.append(subject);
			sb.append("\"&body=\"");
			sb.append(body);
			sb.append("\"&total_fee=\"");
			sb.append(position);
			sb.append("\"&notify_url=\"");

			// 网址需要做URL编码
			sb.append(URLEncoder.encode(url+"/PayCheck/notify_url.jsp"));
			sb.append("\"&service=\"mobile.securitypay.pay");
			sb.append("\"&_input_charset=\"UTF-8");
			sb.append("\"&return_url=\"");
			sb.append(URLEncoder.encode("http://m.alipay.com"));
			sb.append("\"&payment_type=\"1");
			sb.append("\"&seller_id=\"");
			sb.append(Keys.getDEFAULT_SELLER());
			// 如果show_url值为空，可不传
			// sb.append("\"&show_url=\"");
			sb.append("\"&it_b_pay=\"1m");
			sb.append("\"");

			return new String(sb);
		}
		
		
	 private String getOutTradeNo() {
			SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
			Date date = new Date();
			String key = format.format(date);

			java.util.Random r = new java.util.Random();
			key += r.nextInt();
			key = key.substring(0, 15);
			Log.d(TAG, "outTradeNo: " + key);
			return key;
		}

	 Handler mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				Result result = new Result((String) msg.obj);

				switch (msg.what) {
				case RQF_PAY:
				case RQF_LOGIN: {
					String resultKey=result.getResult();
					if (resultKey.equals("9000")){
						//成功
						List<NameValuePair> ls = new ArrayList<NameValuePair>();
						ls.add(new BasicNameValuePair("ghdh", ghdh));
						JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YXTYYGHFF, ls);
						if (json != null && !json.equals(""))
						{
							if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
							{
								try {
									if (json.getString("payflag").equals("SUCCESS")){
										String name = mActivity.getClass().getName();
										if(mActivity.getClass().getName().compareTo("cn.com.winning.ecare.activity.GhSix") == 0) {//
											Button zxff=(Button) mActivity.findViewById(R.id.zxff);//在线支付
											zxff.setText("已付费");
											zxff.setEnabled(false);
										}else{
											Intent intent = new Intent(mActivity, GhSeven.class);
											mActivity.startActivity(intent);
											mActivity.finish();
										}
										
										
										Toast.makeText(mActivity,"支付保存成功",
												Toast.LENGTH_SHORT).show();
									}else{
										Toast.makeText(mActivity,"支付保存失败",
												Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									Toast.makeText(mActivity,"支付保存失败",
											Toast.LENGTH_SHORT).show();
								}
							}else{
								Toast.makeText(mActivity,"支付保存失败",
										Toast.LENGTH_SHORT).show();
							}
						}else{
							Toast.makeText(mActivity,"支付保存失败",
									Toast.LENGTH_SHORT).show();
						}
					}else{
						//失败
					}
					Toast.makeText(mActivity,result.getSResultStatus(result.getResult()),
							Toast.LENGTH_SHORT).show();

				}
					break;
				default:
					break;
				}
			};
		};
}
